<template>
  <div class="video-view">
    <!-- 导航栏 -->
    <div class="navbar">
      <div class="navbar-title">宠物视频</div>
      <div @click="goToUpload">
        <i class="fas fa-upload"></i>
      </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="header">
      <div class="search-bar">
        <i class="fas fa-search search-icon"></i>
        <input 
          type="text" 
          class="search-input" 
          placeholder="搜索视频" 
          v-model="searchQuery"
          @input="handleSearch"
        >
      </div>
    </div>
    
    <!-- 分类导航 -->
    <div class="category-nav">
      <div 
        v-for="(category, index) in categories" 
        :key="index"
        :class="['category-item', { active: currentCategory === category.tagId }]"
        @click="selectCategory(category.tagId)"
      >
        {{ category.name }}
      </div>
    </div>
    
    <!-- 视频列表 -->
    <div class="video-grid" v-if="!loading && videos.length > 0">
      <router-link 
        :to="{ name: 'videoPlayer', params: { id: video.videoId } }" 
        class="video-card" 
        v-for="video in videos" 
        :key="video.videoId"
      >
        <div class="video-thumbnail">
          <img :src="video.coverImage" :alt="video.title">
          <div class="video-play-icon">
            <i class="fas fa-play"></i>
          </div>
          <div class="video-duration">{{ formatDuration(video.duration) }}</div>
          <div class="prod-badge" v-if="video.hasProducts">
            <i class="fas fa-shopping-bag prod-icon"></i>
            <span>购买相关商品</span>
          </div>
        </div>
        <div class="video-info">
          <h3 class="video-title">{{ video.title }}</h3>
          <div class="video-meta">
            <div class="video-author">
              <span>作者: {{ video.authorName }}</span>
            </div>
            <div class="video-stats">
              <div class="stat-item">
                <i class="fas fa-eye stat-icon"></i>
                <span>{{ formatNumber(video.views) }}</span>
              </div>
              <div class="stat-item">
                <i class="fas fa-thumbs-up stat-icon"></i>
                <span>{{ formatNumber(video.likes) }}</span>
              </div>
            </div>
          </div>
        </div>
      </router-link>
    </div>
    
    <!-- 无视频状态 -->
    <div class="no-videos" v-if="!loading && videos.length === 0">
      <div class="empty-icon">
        <i class="fas fa-video-slash"></i>
      </div>
      <p>暂无视频</p>
      <span>换个分类或关键词试试吧</span>
    </div>

    <!-- 加载中状态 -->
    <div class="loading-container" v-if="loading">
      <van-loading type="spinner" size="24px">加载中...</van-loading>
    </div>
    
    <!-- 底部导航栏 -->
    <TabBar active-tab="video" />
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/network/api'
import TabBar from '@/components/TabBar.vue'

export default {
  name: 'VideoView',
  setup() {
    const router = useRouter()
    const videos = ref([])
    const loading = ref(true)
    const categories = ref([])
    const currentCategory = ref(1)
    const searchQuery = ref('')
    const searchTimeout = ref(null)

    // 获取视频分类列表
    const fetchCategories = async () => {
      try {
        const response = await api.getVideoCategories()
        categories.value = response.data.data
      } catch (error) {
        console.error('获取视频分类失败:', error)
      }
    }

    // 获取视频列表
    const fetchVideos = async () => {
      loading.value = true
      try {
        const response = await api.getVideos({
            category: currentCategory.value,
            query: searchQuery.value
        })
        videos.value = response.data.data
      } catch (error) {
        console.error('获取视频列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 选择分类
    const selectCategory = (categoryId) => {
      currentCategory.value = categoryId
    }

    // 处理搜索
    const handleSearch = () => {
      if (searchTimeout.value) {
        clearTimeout(searchTimeout.value)
      }
      searchTimeout.value = setTimeout(() => {
        fetchVideos()
      }, 500)
    }

    // 格式化数字（如1200 -> 1.2万）
    const formatNumber = (num) => {
      if (num == null) {
        return '0'
      }
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      }
      return num.toString()
    }

    // 格式化视频时长（秒转为MM:SS）
    const formatDuration = (seconds) => {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // 前往上传页面
    const goToUpload = () => {
      router.push('/video/upload')
    }

    // 监听分类变化
    watch(currentCategory, () => {
      fetchVideos()
    })

    onMounted(() => {
      fetchCategories()
      fetchVideos()
    })

    return {
      videos,
      loading,
      categories,
      currentCategory,
      searchQuery,
      selectCategory,
      handleSearch,
      formatNumber,
      formatDuration,
      goBack,
      goToUpload,
      TabBar
    }
  }
}
</script>

<style scoped>
/* 导航栏样式 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.8);
  border-bottom: 1px solid #f0f1f2;
  position: sticky;
  top: 0;
  z-index: 10;
  backdrop-filter: blur(10px);
}

.navbar-back {
  font-size: 18px;
  color: #4a5568;
}

.navbar-title {
  font-size: 18px;
  font-weight: 600;
  color: #2d3748;
  flex: 1;
  text-align: center;
  margin-left: -20px;
}

.navbar .fa-upload {
    font-size: 20px;
    color: #323233;
}

/* 头部搜索栏样式 */
.header {
  padding: 10px 15px;
  background-color: white;
  border-bottom: 1px solid #f0f1f2;
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #f7f8fa;
  border-radius: 20px;
  padding: 8px 15px;
}

.search-icon {
  color: #969799;
  margin-right: 8px;
}

.search-input {
  border: none;
  background-color: transparent;
  outline: none;
  flex: 1;
  font-size: 14px;
}

/* 分类导航栏样式 */
.category-nav {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  background-color: white;
  padding: 10px 15px;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}
.category-nav::-webkit-scrollbar {
  display: none; /* Chrome, Safari, and Opera */
}

.category-item {
  padding: 8px 16px;
  color: #646566;
  font-size: 14px;
  border-radius: 18px;
  margin-right: 10px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.category-item.active {
  color: white;
  background-color: #3490dc;
  font-weight: 500;
}

/* 视频卡片样式 */
.video-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 10px;
    padding: 15px;
    padding-bottom: 70px; /* 为底部导航栏留出空间 */
}

.video-card {
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
  text-decoration: none;
  color: inherit;
  display: flex;
  flex-direction: column;
}

.video-thumbnail {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 宽高比 */
}

.video-thumbnail img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 40px;
  height: 40px;
  background-color: rgba(0,0,0,0.4);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: background-color 0.2s;
}

.video-card:hover .video-play-icon {
    background-color: rgba(0,0,0,0.6);
}

.video-play-icon i {
  color: white;
  font-size: 18px;
}

.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background-color: rgba(0,0,0,0.6);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.prod-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  background: linear-gradient(135deg, #ff6a88, #ff99ac);
  color: white;
  padding: 3px 8px;
  border-radius: 12px 4px 12px 4px;
  font-size: 11px;
  display: flex;
  align-items: center;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
}

.prod-icon {
  margin-right: 4px;
  font-size: 10px;
}

.video-info {
  padding: 12px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.video-title {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
  line-height: 1.4;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  min-height: 39px; /* 14px * 1.4 * 2 */
}

.video-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #969799;
  font-size: 12px;
}

.video-author {
  display: flex;
  align-items: center;
}

.video-stats {
  display: flex;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.stat-icon {
  margin-right: 4px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

/* 无视频状态 */
.no-videos {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
  color: #969799;
}

.empty-icon {
  font-size: 48px;
  color: #dcdee0;
  margin-bottom: 16px;
}

.no-videos p {
  font-size: 16px;
  color: #646566;
  margin-bottom: 8px;
}

.no-videos span {
  font-size: 14px;
}

/* 容器样式，为底部导航腾出空间 */
.container {
  padding-bottom: 60px;
}

/* 视图容器 */
.video-view {
  min-height: 100vh;
  background-color: #f7f8fa;
}
</style>
